package main

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"
)

/**
创建elasticsearch客户端
*/
func createEsClient(hosts []string, username string, password string, trace bool, traceLogPath string) (*elastic.Client, error) {
	options := []elastic.ClientOptionFunc{
		elastic.SetURL(hosts...),
		elastic.SetBasicAuth(username, password),
		//elastic.SetSniff(false),
	}
	//开启了trace日志，那么记录trace信息
	if trace {
		var file = os.Stdout
		var err error
		if traceLogPath == "" {
			traceLogPath = "estracelogs"
		}
		PathSeparatorString := string(os.PathSeparator)
		traceLogPath = strings.Trim(traceLogPath, PathSeparatorString)
		//目录不存在则创建
		traceLogPath = strings.ReplaceAll(traceLogPath, "/", PathSeparatorString)
		if _, err := os.Stat(traceLogPath); os.IsNotExist(err) {
			os.MkdirAll(traceLogPath, 0666)
		}
		traceFileRealPath := traceLogPath + PathSeparatorString + time.Now().Format("20060102") + ".log"
		file, err = os.OpenFile(traceFileRealPath, os.O_APPEND, 0666)
		if err != nil && os.IsNotExist(err) {
			file, err = os.Create(traceFileRealPath)
			if err != nil {
				fmt.Println(traceFileRealPath, err)
				file = os.Stdout
			}
		}
		logger := log.New(file, "", log.Ldate|log.Ltime|log.Lshortfile)

		options = append(options, elastic.SetTraceLog(logger))
	}

	client, err := elastic.NewClient(options...)
	if err != nil {
		return nil, err
	}
	return client, nil
}

type DemoItem struct {
	Id       string
	UserName string
}

func main() {
	hosts := []string{
		"http://10.100.6.114:9200",
		"http://10.100.6.114:9201",
		"http://10.100.6.115:9200",
		"http://10.100.6.115:9201",
		"http://10.100.6.115:9202",
	}
	username := "elastic"
	password := "123456"
	trace := false
	traceLogPath := ""

	var cliChan = make(chan *elastic.Client, 5)
	for i := 0; i < 5; i++ {
		conn, err := createEsClient(hosts, username, password, trace, traceLogPath)
		if err != nil {
			panic(err)
		}
		cliChan <- conn
	}

	var wg sync.WaitGroup
	for i := 0; i < 10000; i++ {
		client := <-cliChan
		wg.Add(1)
		go func() {
			defer func() {
				wg.Done()
				cliChan <- client
			}()
			item := DemoItem{
				Id:       strconv.Itoa(int(time.Now().UnixNano())),
				UserName: "喊上",
			}
			client.Index().Index("elasticdemo").
				BodyJson(item).
				Id(item.Id).
				Do(context.Background())
		}()
	}
	wg.Wait()

}
